package com.centling.smartSealForPhone.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.centling.smartSealForPhone.R;
import com.centling.smartSealForPhone.application.SmartSeal;
import com.centling.smartSealForPhone.bean.LoginBean;
import com.centling.smartSealForPhone.bean.VersionBean;
import com.centling.smartSealForPhone.constants.GlobalData;
import com.centling.smartSealForPhone.constants.SPConstants;
import com.centling.smartSealForPhone.constants.UrlConstants;
import com.centling.smartSealForPhone.constants.UserType;
import com.wsdk.service.BluetoothLeService;
import com.centling.smartSealForPhone.utils.GlideApp;
import com.fionera.base.util.MD5Util;
import com.centling.smartSealForPhone.utils.OkHttpUtil;
import com.centling.smartSealForPhone.utils.SPUtil;
import com.centling.smartSealForPhone.utils.ShowToast;
import com.centling.smartSealForPhone.view.VersionDialog;
import com.google.gson.Gson;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.functions.Consumer;

public class LoginActivity
        extends BaseActivity
        implements View.OnClickListener {
    private static final int REQUEST_CODE_PSW = 1003;
    public static final int REQUEST_CODE_SET_IP = 1001;

    private TextView mTvTitle;
    private TextView mTvEditIP;
    private EditText mEtUsername;
    private EditText mEtPsw;
    private ImageView mIvHelp;
    private ImageView mIvRemember;
    private TextView btnLogin;
    private ImageView ivLogo;
    private String userName;
    private String psw;
    private LoginBean loginBean;
    private TextView register;

    @SuppressLint("CheckResult")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        String ip = SmartSeal.getInstance().getIp();
        boolean highQuality = SPUtil.getBoolean(SPConstants.HQ_UPLOAD, true);
        if (!SPUtil.getBoolean(SPConstants.REMEMBERUSER, false)) {
            SPUtil.clearAll();
        } else {
            String userName = SPUtil.getString(SPConstants.USER_NAME);
            String passWord = SPUtil.getString(SPConstants.USER_PSW);
            boolean isRemember = SPUtil.getBoolean(SPConstants.REMEMBERUSER);
            SPUtil.clearAll();
            SPUtil.setString(SPConstants.USER_NAME, userName);
            SPUtil.setString(SPConstants.USER_PSW, passWord);
            SPUtil.setBoolean(SPConstants.REMEMBERUSER, isRemember);
        }
        SmartSeal.getInstance().changeIp(ip);
        SPUtil.setBoolean(SPConstants.HQ_UPLOAD, highQuality);

        initView();

        setListener();

        new RxPermissions(this).request(Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.CALL_PHONE, Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION).subscribe(
                new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean granted) {
                        if (granted) {
                            initData();
                        } else {
                            ShowToast.shortTime("请授予必要的权限");
                            finish();
                        }
                    }
                });
    }

    private void initView() {
        register = findViewById(R.id.regist_textview);
        mTvTitle = findViewById(R.id.login_tv_title);
        mTvEditIP = findViewById(R.id.login_tv_editip);
        mEtUsername = findViewById(R.id.login_et_username);
        mEtPsw = findViewById(R.id.login_et_psw);
        mIvHelp = findViewById(R.id.iv_use_helper);
        mIvRemember = findViewById(R.id.login_iv_remember);
        btnLogin = findViewById(R.id.btn_login);
        ivLogo = findViewById(R.id.iv_login_logo);
        mEtUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                mEtPsw.setText("");
            }
        });
    }

    private void setListener() {
        mTvEditIP.setOnClickListener(this);
        register.setOnClickListener(this);
        mIvHelp.setOnClickListener(this);
        mIvRemember.setOnClickListener(this);
        btnLogin.setOnClickListener(this);
    }

    private void initData() {
        if (SPUtil.getBoolean(SPConstants.REMEMBERUSER)) {
            mEtUsername.setText(SPUtil.getString(SPConstants.USER_NAME));
            mEtPsw.setText(SPUtil.getString(SPConstants.USER_PSW));
            mIvRemember.setSelected(true);
        }
        if (TextUtils.isEmpty(SmartSeal.getInstance().getIp())) {
            startActivityForResult(new Intent(mContext, SetServerIpActivity.class),
                    REQUEST_CODE_SET_IP);
        } else {
            checkIP(SmartSeal.getInstance().getIp());
        }
    }

    /**
     * 检查Ip地址是否可用
     * @param ip ip地址
     */
    private void checkIP(final String ip) {
        UrlConstants.ROOTURL = "" + ip;
        mProcessDialog.setTitle("正在设置服务器地址").showNormal();
        getEnqueue(UrlConstants.BASE_DATA, new OkHttpUtil.NetCallBack() {
            @Override
            public void onSucceed(String json) {
                mProcessDialog.dismiss();
                SmartSeal.getInstance().changeIp(ip);

                JSONObject rawObject = null;
                try {
                    rawObject = new JSONObject(json);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (rawObject != null) {
                    GlobalData.title = rawObject.optString("systemName");
                    GlobalData.adminName = rawObject.optString("systemAdmin");
                    GlobalData.tel = rawObject.optString("phone");
                    GlobalData.appImageLogin = rawObject.optString("appImageLogin");
                    GlobalData.appImageMain = rawObject.optString("appImageMain");
                    GlobalData.appImageEquip = rawObject.optString("appImageEquip");
                    GlobalData.appImageMainAdmin = rawObject.optString("appImageMainAdmin");
                }
                mTvTitle.setText(GlobalData.title);
                GlideApp.with(mContext).load(GlobalData.appImageLogin).placeholder(R.drawable.iv_logo).into(ivLogo);
                checkSoftwareVersion();
            }

            @Override
            public void onFailed(String reason) {
                mProcessDialog.dismiss();
                ShowToast.shortTime(reason);
                startActivityForResult(new Intent(LoginActivity.this, SetServerIpActivity.class),
                        1001);
            }
        });
    }

    /**
     * 检查版本
     */
    private void checkSoftwareVersion() {
        try {
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            final String version = packageInfo.versionName;
            Map<String, String> params = new HashMap<>();
            params.put("softwareVersion", version);
            params.put("flag", "0");
            postJsonEnqueue(UrlConstants.VERSION, params, new OkHttpUtil.NetCallBack() {
                @Override
                public void onSucceed(String json) {
                    VersionBean versionBean = new Gson().fromJson(json, VersionBean.class);
                    if (TextUtils.equals(versionBean.getHasNewVersion(), "1")) {
                        new VersionDialog(LoginActivity.this, versionBean, version).show();
                    }
                }

                @Override
                public void onFailed(final String reason) {
                    ShowToast.shortTime(reason);
                }
            });
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void login() {
        userName = mEtUsername.getText().toString().trim();
        psw = mEtPsw.getText().toString().trim();
        if (TextUtils.isEmpty(userName)) {
            Toast.makeText(LoginActivity.this, "请输入用户名", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(psw)) {
            Toast.makeText(LoginActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
            return;
        }

        mProcessDialog.setTitle("正在登录").showNormal();
        Map<String, String> params = new HashMap<>();
        params.put("username", userName);
        params.put("password", MD5Util.md5(psw));
        postJsonEnqueue(UrlConstants.LOGIN, params, new OkHttpUtil.NetCallBack() {
            @Override
            public void onSucceed(String json) {
                mProcessDialog.dismiss();
                if (mIvRemember.isSelected()) {
                    SPUtil.setString(SPConstants.USER_NAME, userName);
                    SPUtil.setString(SPConstants.USER_PSW, psw);
                }
                // 存储登录返回的信息 json串
                SPUtil.setString(SPConstants.LOGIN_JSON, json);
                loginBean = new Gson().fromJson(json, LoginBean.class);
                SPUtil.setString(SPConstants.EQUIPSN, loginBean.getEquipRegisterInfo().getSn());
                SPUtil.setString(SPConstants.CORE_SN, TextUtils
                        .isEmpty(loginBean.getEquipRegisterInfo().getEmbededSn()) ? loginBean
                        .getEquipRegisterInfo().getSn() : loginBean.getEquipRegisterInfo()
                        .getEmbededSn());
                SPUtil.setString(SPConstants.TOKEN, loginBean.getToken());
                SPUtil.setString(SPConstants.USER_ID, loginBean.getUserLogin().getId());
                SPUtil.setString(SPConstants.USER_TYPE, loginBean.getUserLogin().getUserType());
                SPUtil.setString(SPConstants.AVATAR, loginBean.getUserLogin().getAvatar());
                SPUtil.setString(SPConstants.REAL_NAME, loginBean.getUserLogin().getRealName());
                SPUtil.setString(SPConstants.DEPARTMENT, loginBean.getUserLogin().getDepartment());
                SPUtil.setString(SPConstants.USER_NAME, loginBean.getUserLogin().getUsername());
                SPUtil.setString(SPConstants.PHONE, loginBean.getUserLogin().getPhone());
                SPUtil.setString(SPConstants.ROLENAME, loginBean.getUserLogin().getRoleName());
                SPUtil.setString(SPConstants.RECEIVE_MESSAGE, loginBean.getUserLogin().getReceiveMsg());
                SPUtil.putStrListValue(mContext, SPConstants.AUTHORITY,
                        loginBean.getUserLogin().getAuthority());
                GlobalData.isInFixMode = TextUtils.equals(loginBean.getUserLogin().getEquipRepairStatus(), "1");
                if (loginBean.getUserLogin().getPasswordStatus() != null && "0".equals(
                        loginBean.getUserLogin().getPasswordStatus())) {
                    // 进入修改密码的界面
                    Intent intent = new Intent(LoginActivity.this, ModifySelfPassActivity.class);
                    intent.putExtra("fromLogin", true);
                    startActivityForResult(intent, REQUEST_CODE_PSW);
                    return;
                }
                toForward();

            }

            @Override
            public void onFailed(String reason) {
                mProcessDialog.dismiss();
                ShowToast.shortTime(reason);
            }
        });
    }

    private void toForward() {

        switch (loginBean.getUserLogin().getUserType()) {
            // 设备管理员
            case UserType.EQUIP_ADMIN:
            // 设备操作员
            case UserType.EQUIP_OPERATOR:
                if (TextUtils.equals(loginBean.getEquipRegisterInfo().getEquipStatus(), "-1")) {
                    Intent intent = new Intent(LoginActivity.this, BluetoothListActivity.class);
                    intent.putExtra("loginbean", loginBean);
                    startActivity(intent);
                    finish();
                } else {
                    Intent intent = new Intent(mContext, MainTabsActivity.class);
                    intent.putExtra("fromLogin", true);
                    intent.putExtra("loginbean", loginBean);
                    startActivity(intent);
                    finish();
                }
                break;
            // 普通用章人
            case UserType.EQUIP_COMMON_USER: {
                Intent intent = new Intent(mContext, MainTabsActivity.class);
                intent.putExtra("fromLogin", true);
                intent.putExtra("loginbean", loginBean);
                startActivity(intent);
                finish();
                break;
            }
            // 审核员
            case UserType.SERVER_USER: {
                Intent intent = new Intent(LoginActivity.this, AuditorMainActivity.class);
                intent.putExtra("fromLogin", true);
                intent.putExtra("loginbean", loginBean);
                startActivity(intent);
                finish();
                break;
            }
            default:
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        /*
          login stop service
         */
        stopService(new Intent(mContext, BluetoothLeService.class));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SET_IP && resultCode == RESULT_OK) {
            checkIP(data.getStringExtra("ip"));
        } else if (requestCode == REQUEST_CODE_PSW && resultCode == RESULT_OK) {
            if (mIvRemember.isSelected()) {
                SPUtil.setString(SPConstants.USER_PSW, data.getStringExtra("newpsw"));
            }
            toForward();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.regist_textview:
                mProcessDialog.setTitle("正在连接云注册服务器").showNormal();
                getEnqueue(UrlConstants.BASE_DATA, new OkHttpUtil.NetCallBack() {
                    @Override
                    public void onSucceed(String json) {
                        mProcessDialog.dismiss();
                        Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
                        startActivity(registerIntent);
                    }

                    @Override
                    public void onFailed(String reason) {
                        mProcessDialog.dismiss();
                        ShowToast.shortTime(reason);
                    }
                });
                break;
            case R.id.login_tv_editip:
                startActivityForResult(new Intent(LoginActivity.this, SetServerIpActivity.class),
                        1001);
                break;
            case R.id.login_iv_remember:
                if (SPUtil.getBoolean(SPConstants.REMEMBERUSER)) {
                    mIvRemember.setSelected(false);
                    SPUtil.setBoolean(SPConstants.REMEMBERUSER, false);
                } else {
                    mIvRemember.setSelected(true);
                    SPUtil.setBoolean(SPConstants.REMEMBERUSER, true);
                }
                break;
            case R.id.iv_use_helper:
                startActivity(new Intent(mContext, InstructionActivity.class));
                break;
            case R.id.btn_login:
                login();
                break;
            default:
                break;
        }
    }
}
